package serverapp;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author a
 */
public class ConnectionHandler implements Runnable {

        private Socket server;
        private OutputStream out;
        private InputStream in;
        private ObjectInputStream inObject;
        private ObjectOutputStream outObject;
        private ArrayList players;

        public ConnectionHandler(Socket aServer) {
            this.server = aServer;
        }

        @Override
        public void run() {
            try {
                out = server.getOutputStream();
                in = server.getInputStream();
                while(true){
                while (in.available() > 0) {
                            players = getPlayers();
                            for(int i=0;i<players.size();i++){
                                Player player = (Player)players.get(i);
                                int id = player.id;
                                for(int j=0;j<ServerView.players.size();j++){
                                    Player player2 = (Player)ServerView.players.get(i);
                                    int id2 = player2.id;
                                    if(id==id2){
                                        ServerView.players.remove(j);
                                        ServerView.players.add(player);
                                        break;
                                    }
                                }
                            }
                }
                }
            } catch (IOException ex) {
                Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public ArrayList getPlayers() {
        ArrayList playerList = new ArrayList();
        try {
            System.out.println("Receiving players ...");
            inObject = new ObjectInputStream(server.getInputStream());
            playerList = (ArrayList) inObject.readObject();
            System.out.println("Players received.");
        } catch (IOException ex) {
            Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return playerList;
    }

        public void sendPlayers(ArrayList aPlayerList) {
            try {
                System.out.println("Sending players ...");
                outObject = new ObjectOutputStream(server.getOutputStream());
                outObject.writeObject(aPlayerList);
                System.out.println("Players sent");
            } catch (IOException ex) {
                Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }